import os
import glob
import sys
from ExcelAPI import *
from SVDClasses import *
from Utility import *
from ExtractStartS_CM4 import *

script_version = "0.3.0"
version_str = f"PySVDAssistant Version:{script_version}"

def print_usage():
    print(f"{version_str}")
    print("py  Usage: python PySVDAssistant.py [Options] [input xlsx paths or files...]")
    print("exe Usage: PySVDAssistant.exe       [Options] [input xlsx paths or files...]")
    print("Options:")
    print("  -SVDOut=SVDOutPutDirPath    Specify the output dir path of SVD file (default: ./)")
    print("  -RTLOut=RTLOutPutDirPath    Specify the output dir path of RTL file (default: ./)")
    print("  -DisableSVD                 Disable SVD Conversion")
    print("  -DisableRTL                 Disable RTL Conversion")

  
  
if __name__ == "__main__":
    svdoutputDir = "./"
    rtloutputDir = "./"
    file_paths = []

    Enable_SVDConver = True
    Enable_RTLConver = True
    DebugMode = False
    
    # 处理命令行参数
    for arg in sys.argv[1:]:
        if arg.startswith("-SVDOut="):
            svdoutputDir = arg.split("=", 1)[1]  # 获取输出文件路径
        elif arg.startswith("-RTLOut="):
            rtloutputDir = arg.split("=", 1)[1]  # 获取输出文件路径
        elif arg.startswith("-DisableSVD"):
            Enable_SVDConver = False
        elif arg.startswith("-DisableRTL"):
            Enable_RTLConver = False
        elif arg.startswith("-Debug"):
            DebugMode = True
        else:
            file_paths.append(arg)  # 收集输入参数

    # 如果没有输入参数，默认使用当前文件夹
    if not file_paths:
        file_paths = [os.getcwd()]

        
    print("**********************************************")
    print_usage()
    print("**********************************************")

    # 检查输入参数数量
    if len(file_paths) < 1:  # 至少要有一个输入路径
        sys.exit(1)
        
    # 获取所有 XLSX 文件
    all_file_paths = []
    for path in file_paths:
        if os.path.isdir(path):
            all_file_paths.extend(get_xlsx_files(path))
        else :
            if path.startswith("~$") : # 排除临时文件
                continue                        
            if not path.endswith('.xlsx') :
                continue            
            all_file_paths.append(path)

    # 确保至少有一个 XLSX 文件
    if not all_file_paths:
        print(f"[Error]No XLSX files found in the specified paths!")
        print_usage()
        sys.exit(1)

    # 从 Excel 文件中提取所有必要信息
    svd_info = get_infos_from_excels(all_file_paths)
    if svd_info is None:
        print(f"[Error]Fail to get svd_info info!!!")
        sys.exit(2)

    exit_code = 0
    if Enable_SVDConver :
        # 根据提取的信息生成 svd 字符串
        svd_string = gen_svd_string_from_info(svd_info)
        if svd_string is None or svd_string == '':
            exit_code = 1
            print(f"[Error]Fail to generate svd_string info!!!")
        else :
            # 保存到文件
            TargetName = svd_info['device']['name']
            outputfile = os.path.join(svdoutputDir, TargetName + ".svd")
            save_to_file(outputfile, svd_string)
            
            #生成StartS文件
            svdhfile = os.path.join(svdoutputDir, TargetName + ".h")
            if os.path.exists(outputfile) and os.path.exists(svdhfile):
                ExtractStartS_CM4("RJMICRO",TargetName,svdoutputDir,outputfile,svdhfile,"V1.00")

    if Enable_RTLConver :
        gen_rtlreg_string_from_info(svd_info,rtloutputDir)
        
    
    if not DebugMode :
        sys.exit(exit_code)  # 正常退出

        
